package com.caigp.cookbook2.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.caigp.cookbook2.R;
import com.caigp.cookbook2.adapter.MainFragmentPagerAdapter;
import com.caigp.cookbook2.base.BaseActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private String[] titles = {"搜索", "分类", "更多"};

    private int page;

    @BindView(R.id.view_pager)
    ViewPager viewPager;

    @BindView(R.id.bottom_nav_view)
    BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setActionBarTitle(titles[page]);
        ButterKnife.bind(this);
        initViewPager();
        initBottomNavigationView();
    }

    @Override
    protected boolean showHomeAsUp() {
        return false;
    }

    private void initBottomNavigationView() {
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.bottom_nav_search:
                        page = 0;
                        break;
                    case R.id.bottom_nav_menu:
                        page = 1;
                        break;
                    case R.id.bottom_nav_more:
                        page = 2;
                        break;
                }
                viewPager.setCurrentItem(page);
                setActionBarTitle(titles[page]);
                return true;
            }
        });
    }

    private void initViewPager() {
        MainFragmentPagerAdapter fragmentPagerAdapter = new MainFragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                //Log.d(TAG, "onPageSelected: " + position);
                bottomNavigationView.getMenu().getItem(position).setChecked(true);
                page = position;
                setActionBarTitle(titles[position]);
            }
        });
    }
}
